/**
 * 
 */
package com.dingjian.meal.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.dingjian.base.dao.BaseDao;
import com.dingjian.base.util.StringUtils;
import com.dingjian.basedata.service.impl.DataEntityService;
import com.dingjian.meal.dao.DishesDao;
import com.dingjian.meal.dao.RestaurantDao;
import com.dingjian.meal.model.Dishes;
import com.dingjian.meal.model.Restaurant;
import com.dingjian.meal.service.RestaurantService;

/**
 *
 * @author FengMy
 * @since 2012-6-8
 */
@Component(value="restaurantService")
@Transactional
public class RestaurantServiceImpl extends DataEntityService<Restaurant> implements
	RestaurantService {
	@Resource(name="restaurantDao")
	private RestaurantDao restaurantDao;
	@Resource(name="dishesDao")
	private DishesDao dishesDao;
	
	@Override
	protected BaseDao getDao() {
		return restaurantDao;
	}
	
	@Override
	public void addEntity(Restaurant restaurant) {
		restaurant.setId(UUID.randomUUID().toString());
		List<Dishes> dishes = restaurant.getDishes();
		for(Dishes d : dishes){
			d.setRestaurant(restaurant);
			d.setId(UUID.randomUUID().toString());
			dishesDao.addEntity(d);
		}
		super.addEntity(restaurant);
	}
	@Override
	public void updateEntity(Restaurant restaurant) {
		Restaurant old = getEntityById(restaurant.getId());
		List<Dishes> olddishes = old.getDishes();
		List<Dishes> dishes = restaurant.getDishes();
		List<Dishes> updateDishes = new ArrayList<Dishes>(dishes);
		List<Dishes> newdishes = new ArrayList<Dishes>();
		for(Dishes d : dishes){
			d.setRestaurant(restaurant);
			if(StringUtils.isEmpty(d.getId())){
				d.setId(UUID.randomUUID().toString());
				newdishes.add(d);
				updateDishes.remove(d);
			}else{
				for(Dishes o : olddishes){
					if(o.getId().equals(d.getId())){
						olddishes.remove(o);
						break;
					}
				}
			}
		}
		for(Dishes o : olddishes){
			dishesDao.deleteById(o.getId());
		}
		for(Dishes o : newdishes){
			dishesDao.addEntity(o);
		}
		for(Dishes o : updateDishes){
			dishesDao.updateEntity(o);
		}
		super.updateEntity(restaurant);
	}
	@Override
	public void deleteById(String id) {
		dishesDao.deleteByResaurantId(id);
		super.deleteById(id);
	}
	
	public void enable(String id, boolean enable) {
		Restaurant restaurant = getEntityById(id);
		restaurant.setEnable(enable);
		restaurantDao.updateEntity(restaurant);
	}
}
